package com.example.wxy.bbtapp.Common;

import com.example.wxy.bbtapp.Service.BindService;
import com.example.wxy.bbtapp.myApplication;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Date;

/**
 * Created by yons on 2017/9/12.
 */

public class HttpHelper {

    JSONObject obj = new JSONObject();
    String path = "";
    String basePath = "";

    public HttpHelper(String ApiPath)
    {
        basePath = myApplication.bindinofs.getServerUrl();
        path = ApiPath;
    }

    public HttpHelper(String BasePath, String ApiPath)
    {
        basePath = BasePath;
        path = ApiPath;
    }

    public HttpHelper addParameter(String Name, Object Value)
    {
        try
        {
            obj.put(Name, Value);//根据实际需求添加相应键值对
        }
        catch (JSONException e)
        {

        }
        return this;
    }

    public interface checkTokenOutCallBack
    {
        public void callback();
    }

    public static void checkTokenOut(final checkTokenOutCallBack callBack)
    {
        long diff =new Date().getTime() -  myApplication.TokenTime.getTime();
        if(((diff / (60 * 1000))) > 20)
        {
            BindService.getCook(new httpCallBack<String>("获取Token"){
                @Override
                public void onSuccess(String result) {
                    if(callBack != null)
                    {
                        callBack.callback();
                    }
                }
            });
        }
        else
        {
            if(callBack != null)
            {
                callBack.callback();
            }
        }
    }

    public void post(final httpCallBack<String> callBack)
    {
        final String Path = this.path;
        long diff =new Date().getTime() -  myApplication.TokenTime.getTime();
        if(!Path.equals("RestApi/SysUser/login") && ((diff / (60 * 1000))) > 20)
        {
            BindService.getCook(new httpCallBack<String>("获取Token"){
                @Override
                public void onSuccess(String result) {
                    RequestParams params = new RequestParams(basePath + Path);
                    params.setAsJsonContent(true);
                    params.addHeader("Authorization", myApplication.Token);
                    params.setBodyContent(obj.toString());
                    x.http().post(params,callBack);
                }
            });
        }
        else
        {
            RequestParams params = new RequestParams(basePath +this.path);
            params.setAsJsonContent(true);
            params.addHeader("Authorization", myApplication.Token);
            params.setBodyContent(obj.toString());
            x.http().post(params,callBack);
        }



    }

}
